package com.xbongbong.paas.controller.login;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.service.LoginService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.login.pojo.dto.AutoLoginDTO;
import com.xbongbong.pro.login.pojo.vo.AutoLoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 登录相关接口
 * @author kaka
 * @date 2019/4/17 21:06
 * @since v1.0
 * @version v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/login")
public class BeforeLoginController {

    private static  final Logger LOG = LoggerFactory.getLogger(BeforeLoginController.class);

    @Resource
    private LoginService loginService;

    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String autoLogin(@RequestBody @Valid AutoLoginDTO autoLoginDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
        XbbResponse<AutoLoginVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                AutoLoginVO autoLoginVO = loginService.autoLogin(autoLoginDTO, request, httpResponse);
                response = new XbbResponse<>(autoLoginVO);
            } catch (XbbException xe) {
                response = new XbbResponse<>(xe);
            }
        }
        return JSON.toJSONString(response);
    }
}
